package org.celstec.mobilegame.locatory;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.ForeignKey;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.celstec.mobilegame.gamaray.Asset;
import org.celstec.mobilegame.gamaray.Feature;
import org.celstec.mobilegame.gamaray.FeatureImg;
import org.celstec.mobilegame.server.PMF;
import org.celstec.mobilegame.server.SubmitGameServiceImpl;
import org.celstec.mobilegame.util.WorldObject;
import org.jdom.Element;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class CardLocation implements WorldObject {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	public Key id;
	
	@Persistent
	public double lat;
	
	@Persistent
	public double lon;
	
	@Persistent
	public int onDistance;
	
	@Persistent
	public String cardId;
	
	@Persistent(defaultFetchGroup="true")
	@ForeignKey(table = "org.celstec.mobilegame.locatory.Card")
	public Key card;
	
//	@Persistent
//	public String id="";
	
	@Persistent(defaultFetchGroup="true")
	public Key locatory;
	
	public Key getCard(){
		return card;
	}
	
	public static CardLocation getObject (Key k){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			return (CardLocation) pm.getObjectById(CardLocation.class, k);
		} finally {			
			pm.close();

		}
	}
	
	public CardLocation(){
//		key = KeyFactory.createKey(CardLocation.class.getSimpleName(), ""+System.currentTimeMillis());

	}
	
	public CardLocation(Element location){
		this();
		if (location.getAttributeValue("lat")!= null) lat = Double.parseDouble(location.getAttributeValue("lat"));
		if (location.getAttributeValue("lon")!= null) lon = Double.parseDouble(location.getAttributeValue("lon"));
		if (location.getAttributeValue("onDistance")!= null) onDistance = Integer.parseInt(location.getAttributeValue("onDistance"));
		if (location.getAttributeValue("cardId")!= null) cardId = location.getAttributeValue("cardId");

	}
	
	public String toString(){
		return "CardLocation: "+lat+" "+lon+" "+Card.getObject(card).cardId+" "+onDistance +" ( "+Card.getObject(card).cardId+" "+Card.getObject(card).cardImageType+" "+Card.getObject(card).cardImage+")";
	}

	public double getLat() {
		return lat;
	}

	public double getLon() {
		return lon;
	}
	
	public Asset getAsset(){
		Asset returnAsset = new Asset(Card.getObject(card).cardImageType, Card.getObject(card).cardImage, "asset_cl_"+id);
		return returnAsset;
	}
	
	public Feature getFeature(){
		return new FeatureImg("zone_"+id, "asset_cl_"+id, lat, lon, "CC", null);
	}


}
